import { _decorator, Component, instantiate, Node, NodePool, Prefab, tween, Vec3 } from 'cc';
import { Game } from '../Game';
import { Block } from './Block';
const { ccclass, property } = _decorator;

@ccclass('BlockManager')
export class BlockManager {
    static _instance: BlockManager;
    static get instance() {
        if (this._instance == null) {
            this._instance = new BlockManager();
        }
        return this._instance;
    }
    private blockPool: NodePool = new NodePool();

    // public createBlockPool(){
    //     this.blockPool = new NodePool();
    // }
    /** 创建障碍物 */
    public createBlock(pos_dian: Vec3, blockType: number, index: number,nodeBlock:Node,prefab:Prefab): Block {
        let block: Node = null;
        if (this.blockPool.size() > 0) {
            block = this.blockPool.get();
        } else {
            block = instantiate(prefab);
        }
        nodeBlock.addChild(block);
        const blockComp = block.getComponent(Block);
        blockComp.Init(pos_dian, blockType, index);
        return blockComp;
    }

    /** 获取最近障碍物坐标 */
    getLastBlockPos(nodeBlock:Node): Vec3 {
        return nodeBlock.children[nodeBlock.children.length - 1].getComponent(Block).pos_dianWorldPos;
    }

    /** 创建下一个障碍物 */
    createNextBlock(nodeBlock:Node,prefab:Prefab,bolckDirection:Vec3,blockIndex:number) {
        this.cleanOutScreenBlock(nodeBlock);
        const beginPos = this.getLastBlockPos(nodeBlock);
        var f_random = 290 + Math.random() * 100;
        if (Math.random() * 2 - 1 > 0) {
            bolckDirection.x = bolckDirection.x * -1
        }
        const endPos = new Vec3(beginPos.x + bolckDirection.x * f_random, beginPos.y + bolckDirection.y * f_random);

        this.createBlock(endPos, Math.floor(Math.random() * 22), blockIndex,nodeBlock,prefab);
    }

    /** 清除所有障碍物 */
    cleanAllblock(nodeBlock:Node) {
        var children = nodeBlock.children;
        for (let i = children.length - 1; i >= 0; i--) {
            var js = children[i].getComponent(Block);
            if (js) {
                tween(children[i]).stop();
                this.onBlockKilled(children[i]);
            }
        }
    }

    /** 清除超出屏幕范围的障碍物 */
    cleanOutScreenBlock(nodeBlock:Node) {
        var children = nodeBlock.children;
        for (let i = children.length - 1; i >= 0; i--) {
            var js = children[i].getComponent(Block);
            if (js) {
                if (js.pos_dianWorldPos.y < -900) {
                    this.onBlockKilled(children[i]);
                }
            }
        }
    }

    /** 杀死不需要的方块（将其放入对象池） */
    onBlockKilled(block: Node) {
        this.blockPool.put(block);
    }
}


